<?php
/**
 * Created by PhpStorm.
 * User: Powerless
 * Date: 17/05/04
 * Time: 16:35
 */

class Videos
{

    const BIZID = '5853'; //bizid您在腾讯云分配到的bizid
    //个人 API 密钥
    const SECRETID = 'AKIDBGZmyTg8B7vYbPNgyBC6pRq3FE1xNUzI';
    const SECRETKEY = '1FMI2bO3Xo5EB2qZxQjqW4UikcM2bzFK';
    /*
    //项目密钥
    const SECRETID = 'AKIDhcOhifyN2f9Ueh4JtIXr6KQM7jAQqgfT';
    const SECRETKEY = 'nPzFHFTYUWRBpaQfpcpxxmflyOGSo8Hd';
    */
    const SIGNATURE = '';
    //文档地址
    //https://www.qcloud.com/document/product/266/7788
    const API_BASE_LIVE_URL_PREFIX = 'https://vod.api.qcloud.com/v2/index.php?';//视频转码
    const API_BASE_LIVE_URL_POST = 'POSTvod.api.qcloud.com/v2/index.php?';//生成请求签名的提交地址


    //视频管理
    const GETVIDEOINFO = 'GetVideoInfo'; //获取视频信息
    const DESCRIBEVODPLAYINFO = 'DescribeVodPlayInfo'; //依照视频名称前缀获取视频信息
    const MODIFYVODINFO = 'ModifyVodInfo'; //修改视频属性
    const DELETEVODFILE = 'DeleteVodFile'; //删除视频

    //视频处理
    const CONVERTVODFILE = 'ConvertVodFile'; //视频转码
    const CONCATVIDEO = 'ConcatVideo'; //视频拼接

    //视频分类管理
    const CREATECLASS = 'CreateClass'; //创建视频分类

    /**
     * GET 请求
     * @param string $url
     * @return string content
     */
    private function httpGet($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function httpPost($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    public function checkAuth ()
    {
        $date = [
            'SecretId' => self::SECRETID,
            'Timestamp' => strtotime(date('Y-m-d H:i'))+300,
            'Nonce' => rand(1000,9999),
            'Region' => 'bj',
            'SignatureMethod' => 'HmacSHA256',
        ];
        return $date;
    }

    /**********************************************
     *
     * 视频管理
     *
     **********************************************/

    /**
     * 获取视频信息V2
     * @param string $fileId 希望获取的视频的ID
     * @return string $json 返回结果
     */
    public function getVideoInfo($fileId)
    {
        $data = array(
            'Action' => self::GETVIDEOINFO,
            'fileId' =>$fileId,
        );
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            $all=[];
            foreach ($json['transcodeInfo']['transcodeList'] as $k=>$v){
                $url = parse_url($v['url']);
                $v['url'] = 'https://'.$url['host'].$url['path'];
                $all[] = $v;
            }
            $ret['idrAlignment'] = $json['transcodeInfo']['idrAlignment'];
            $ret['transcodeList'] = $all;
            return $ret;
        }
        return false;
    }


    /**
     * 依照视频名称前缀获取视频信息
     * @param string $fileName 可用开播房间号获取到
     * @return string $json 返回结果
     */
    public function describeVodPlayInfo($fileName,$bizId = self::BIZID)
    {
        $liveCode = $bizId."_".$fileName; //直播码
        $data = array(
            'Action' => self::DESCRIBEVODPLAYINFO,
            'fileName' =>$liveCode,
        );
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            return $json['fileSet'];
        }
        return false;
    }

    /**
     * 修改视频属性
     * @param string $fileId 视频ID
     * @param string $classId 分类ID
     * @return string $json 返回结果
     */
    public function modifyVodInfo($fileId,$classId)
    {
        $data = array(
            'Action' => self::MODIFYVODINFO,
            'fileId' =>$fileId,
            'classId' =>$classId,
        );
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            return '修改成功';
        }
        return false;
    }

    /**
     * 删除视频
     * @param string $fileId 视频ID
     * @return string $json 返回结果
     */
    public function deleteVodFile($fileId)
    {
        $data = array(
            'Action' => self::DELETEVODFILE,
            'fileId' =>$fileId,
            'priority' =>0,
        );
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            return '删除成功';
        }
        return false;
    }


    /**********************************************
     *
     * 视频处理
     *
     **********************************************/
    /**
     * 视频转码
     * @param string $fileId 视频ID
     * @return string $json 返回结果
     */
    public function convertVodFile($fileId)
    {
        $data = array(
            'Action' => self::CONVERTVODFILE,
            'fileId' =>$fileId,
        );
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            return $json['vodTaskId'];
        }
        return false;
    }

    /**
     * 视频拼接
     * @param array $files 视频ID
     * @param string $name 保存名称
     * @return string $json 返回结果
     */
    public function concatVideo($files,$name)
    {
        $file = null;
        $data = array(
            'Action' => self::CONCATVIDEO,
            'name' =>$name,
            'dstType.0' =>'m3u8',
        );
        $file = null;
        foreach ($files as $k => $v){
            $file['srcFileList.'.$k.'.fileId'] = $v['fileId'];
        }
        $data =array_merge($file,$data);
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            return $json['vodTaskId'];
        }
        return false;
    }

    /**********************************************
     *
     * 视频分类管理
     *
     **********************************************/
    /**
     * 创建视频分类
     * @param string $className 分类信息
     * @param string $parentId 父ID
     * @return string $json 返回结果
     */
    public function createClass($className,$parentId = null)
    {
        $data = array(
            'Action' => self::CREATECLASS,
            'className' =>$className,
        );
        if($parentId){
            $data2 = array(
                'parentId'=>$parentId,
            );
            $data =array_merge($data,$data2);
        }
        $data =array_merge($this->checkAuth(),$data);
        ksort($data);
        $str = self::API_BASE_LIVE_URL_POST.http_build_query($data);
        $signature = base64_encode(hash_hmac('sha256', $str, self::SECRETKEY, true));
        $data2 = array(
            'Signature' => $signature,
        );
        $data =array_merge($data,$data2);
        $result = $this->httpPost(self::API_BASE_LIVE_URL_PREFIX , $data);
        if ($result) {
            $json = json_decode($result, true);
            if ($json['code']) {
                return $json['message'];
            }
            return $json['newClassId'];
        }
        return false;
    }


    public function getPlayUrl($streamId,$bizId = self::BIZID)
    {
        $livecode = $bizId.'_'.$streamId; //直播码
        $url = array(
            'rtmp://'.$bizId.'.liveplay.myqcloud.com/live/'.$livecode,
            'https://'.$bizId.'.liveplay.myqcloud.com/live/'.$livecode.'.flv',
            'https://'.$bizId.'.liveplay.myqcloud.com/live/'.$livecode.'.m3u8'
        );
        return $url;
    }
}